<template>
  <div>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="showDialog"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :show-close="false"
      @open="onDialogOpen"
    >
      <upload-file-content :refreshTimes="showDialogTimes" v-show="!resolving"></upload-file-content>
      <resolve-step v-show="resolving" :presentStep="presentStep" :steps="stepDescList"></resolve-step>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="startResolveMessage" v-show="!resolving">上传完毕开始解析</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { Dialog, Button } from 'element-ui';
import UploadFileContent from './UploadFileContent';
import ResolveStep from './ResolveStep';
import { startResolveMessage, checkResolveMessageStatus } from '@/api/bank-financing.js';
export default {
  name: 'upload-dialog',
  components: {
    [Dialog.name]: Dialog,
    [Button.name]: Button,
    UploadFileContent,
    ResolveStep
  },
  props: {
    showDialog: Boolean
  },
  data () {
    return {
      showDialogTimes: 0,
      statusInterval: null,
      resolving: false,
      presentStep: null,
      stepDescList: []
    };
  },
  computed: {
    dialogTitle () {
      return this.resolving ? '报文解析进度' : '上传理财报文'
    }
  },
  methods: {
    closeDialog () {
      if (this.statusInterval != null) {
        clearInterval(this.statusInterval);
        this.statusInterval = null;
      }
      this.$emit('closeDialog');
    },
    onDialogOpen () {
      this.showDialogTimes++;
      this.setStatusInterval();
    },
    startResolveMessage () {
      startResolveMessage()
        .then((res) => {
          this.setStatusInterval();
        }).catch((errMsg) => {
          this.$alert(errMsg.msg);
        })
    },
    setStatusInterval () {
      if (this.statusInterval != null) {
        clearInterval(this.statusInterval);
      }
      this.statusInterval = setInterval(() => {
        checkResolveMessageStatus().then(res => {
          if (res.statusCode == 0) {
            this.resolving = true;
          } else {
            this.resolving = false;
            this.showDialogTimes++;
            if (this.statusInterval != null) {
              clearInterval(this.statusInterval);
              this.statusInterval = null;
            }

            return;
          }
          this.presentStep = res.step;
          this.stepDescList = res.stepDescList;
        }).catch(errMsg => {
          clearInterval(this.statusInterval);
          this.resolving = false;
          this.showDialogTimes++;
          this.$alert(errMsg.msg);
        })
      }, 500);
    }
  }

}
</script>
<style lang="stylus" scoped></style>